package com.jcli.jb51_net.article._131288_图片窗口透明背景;

import com.sun.awt.AWTUtilities;

import javax.swing.*;
import java.awt.*;

/**
 * TODO 图片透明背景
 *上面的程序主要代码在于:设置JFrame为透明，JFrame去掉边框，设置内容面板为透明，然后将图片画到内容面板上。
 * @author li
 * @version 1.0
 * @belongsProject novel_20230923
 * @belongsPackage com.jcli.jb51_net.article._131288_图片窗口透明背景
 * @className MyJframe
 * @createTime 2024-02-23  20:34
 */
public class MyJFrame extends JFrame {
    private float alpha;

    public MyJFrame(String bgPath, float alpha) {
        super();
        myContentPane rp = new myContentPane(bgPath);
        rp.setOpaque(false);//设置内容面板为透明
        this.setContentPane(rp);
        this.setUndecorated(true);
        this.setSize(rp.img.getIconWidth(), rp.img.getIconHeight());
        AWTUtilities.setWindowOpaque(this, false);//设置JFrame为透明
        this.alpha = alpha;
    }

    private class myContentPane extends JPanel {
        public ImageIcon img;

        public myContentPane(String bgPath) {
            super();
            //使用绝对路径而不是相对路径
            //this.img = new ImageIcon(Test.class.getResource(bgPath));
            this.img = new ImageIcon(bgPath);
        }

        @Override
        protected void paintComponent(Graphics g) {
            AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
            Composite old = ((Graphics2D) g).getComposite();
            ((Graphics2D) g).setComposite(ac);
            if (img != null) {
                g.drawImage(img.getImage(), 0, 0, getWidth(), getHeight(), this);
            }
            ((Graphics2D) g).setComposite(old);
            super.paintComponent(g);
        }

    }
}
